package start.spring.basic.config;

import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * ****************************************************************************
 * 自定义动态路由更新
 *
 * @author(作者)：xuyongyun	
 * @date(创建日期)：2023年2月6日
 ******************************************************************************
 */
//@Component
public class CustomRouteDefinitionRepository implements RouteDefinitionRepository,ApplicationEventPublisherAware {

	private ApplicationEventPublisher applicationEventPublisher;
	
	@Override
	public Flux<RouteDefinition> getRouteDefinitions() {
//		List<RouteDefinition> routeDefinitionList = new ArrayList<>();
//        redisTemplate.opsForHash().values(GATEWAY_ROUTES).stream()
//                .forEach(routeDefinition -> routeDefinitionList.add(JSON.parseObject(routeDefinition.toString(), RouteDefinition.class)));
//        return Flux.fromIterable(routeDefinitionList);
		return null;
	}

	@Override
	public Mono<Void> save(Mono<RouteDefinition> route) {
//		return route.flatMap(routeDefinition -> {
//            redisTemplate.opsForHash().put(GATEWAY_ROUTES, routeDefinition.getId(), JSONObject.toJSONString(routeDefinition));
//            redisTemplate.opsForValue().set(GATEWAY_ROUTES_VERSION, String.valueOf(System.currentTimeMillis()));
//            return Mono.empty();
//        });
		return null;
	}

	@Override
	public Mono<Void> delete(Mono<String> routeId) {
//		return routeId.flatMap(id -> {
//            if (redisTemplate.opsForHash().hasKey(GATEWAY_ROUTES, id)) {
//                redisTemplate.opsForHash().delete(GATEWAY_ROUTES, id);
//                redisTemplate.opsForValue().set(GATEWAY_ROUTES_VERSION, String.valueOf(System.currentTimeMillis()));
//            }
//            return Mono.empty();
//        });
		return null;
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}
	
	/**
     * 刷新路由
     *	
     * @since           1.0
     */
    public void refreshRoutes() {
    	applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
    }

}
